<template>
<q-dialog class="machine-file-dialog dialog" v-model="show" persistent>
  <q-card style="min-width: 560px" class="no-shadow dialog-content">
    <q-card-section class="dialog-title bg-primary">
      <div class="text-center text-white">
        从机台选择
      </div>
    </q-card-section>
<!--    筛选条件-->
    <q-card-section class="form-inline">
      <select-tree label="所在位置" :sel-tree="location" class="margin-r-15 margin-t-20" ref="selectTree"
                   :tree-list="locationOptions" node-key="hash" @treeChange="_changeTreeNode"/>
      <q-select class="select"
                outlined dense hide-selected fill-input map-options options-dense use-input
                @filter="filterMachineFn"
                :options="machineOptions"
                @input="changeMachine"
                v-model="machine">
        <template v-slot:option="scope">
          <q-item v-bind="scope.itemProps"
                  v-on="scope.itemEvents">
            <q-item-section>
              <q-item-label v-html="scope.opt.name"></q-item-label>
            </q-item-section>
            <q-item-section side>
              <q-item-label v-html="scope.opt.value" />
            </q-item-section>
          </q-item>
        </template>
        <template v-slot:before>
          <span class="form-name">加工设备:</span>
        </template>
        <template v-slot:append>
          <q-icon name="close" v-if="machine !== null" @click="machine = null" class="cursor-pointer" />
        </template>
      </q-select>
    </q-card-section>
<!--    文件列表-->
    <div class="content relative-position" v-show="tabList.length > 0">
      <q-tabs
        v-model="tab"
        shrink stretch dense
        inline-label
        align="left"
        active-color="primary"
        indicator-color="primary"
        @input="changeStore"
      >
        <q-tab v-for="(tab, tabIndex) in tabList" :key="tabIndex"
               :name="tab.position" :label="tab.label" />
      </q-tabs>
<!--      返回-->
      <q-btn @click="back" class="back-btn" flat round dense size="sm" icon="iconfont icontubiao-58"></q-btn>

      <q-scroll-area
        :thumb-style="CommonConfig.thumbStyle"
        style="height: 210px"
        class="bg-white scorll-content"
      >
        <div class="file-list">
          <file-item v-for="(file, fileIndex) in files" :key="fileIndex" :is-show-menu="false"
                     :file="file" :file-index="fileIndex"
                     :is-active="actFile&&actFile.id===file.id&&actFile.boxId===file.boxId&&actFile.position===file.position"
                     @selFiles="setFile" @dblclickE="dblclickE"
          />
        </div>
      </q-scroll-area>
      <q-inner-loading :showing="fileLoading">
        <q-spinner-gears size="50px" color="primary" />
      </q-inner-loading>
    </div>
<!--    底部确认取消-->
    <q-card-section class="dialog-footer text-center margin-t-10 margin-b-10 no-padding">
      <q-btn class="btn q-mr-md" outline label="取消" color="primary" @click="hideDialog" />
      <q-btn class="btn" unelevated label="确认" color="primary" @click="submit" />
    </q-card-section>
  </q-card>
</q-dialog>
</template>

<script>
import SelectTree from 'src/components/select-tree'
import FileItem from './file-item'
import { getOrganize } from 'src/boot/tpm/equipment-record'
import { getEquipmentAccount } from 'src/boot/program/G-gov'
import { getStoreInfo, getFileInfo } from 'src/boot/program/machine'
import { defaultSchemesClearer, getFiletype } from 'src/assets/js/util'
import boxCodeErr from 'src/assets/json/boxCodeErr'
export default {
  name: 'machine-file-dialog',
  props: {
    client: {},
    // mqtt唯一标识
    requestId: {
      type: String
    }
  },
  data () {
    return {
      show: false, // 控制弹框显示
      location: { // 所在位置
        id: null,
        level: null,
        label: '',
        hash: ''
      },
      locationOptions: [], // 所在位置数据源
      machine: null, // 所选设备
      machineOptions: [], // 设备列表
      tab: '', // 选中的tab值
      tabList: [], // 内部存储，外部存储数据
      boxId: null, // 订阅的盒子id
      files: [], // 文件列表数据
      actFile: null,
      clickTime: null, // 区分单击与双击
      fileLoading: false, // 文件数据加载
      curDirPath: null // 当前选中的目录路径
    }
  },
  methods: {
    showDialog () {
      this.show = true
      this.clearInfo()
      this.getInfoList()
    },
    hideDialog () {
      this.show = false
    },
    // 弹框重新打开时，清空上次浏览的结果
    clearInfo () {
      this.location = {
        id: null,
        level: null,
        label: '',
        hash: ''
      }
      this.machine = null
      this.machineOptions = []
      this.tab = ''
      this.tabList = []
      this.boxId = null
      this.files = []
      this.actFile = null
      this.curDirPath = null
    },
    getInfoList () {
      // 获取组织机构树
      getOrganize().then(res => {
        // 去除 default 节点
        let clearTree = defaultSchemesClearer.clear(res.data)

        this.locationOptions = clearTree
        this.location = Object.assign({}, clearTree[0])
        console.log(this.location)

        this.$refs.selectTree.setValue(this.location)

        this._changeTreeNode(this.location)
      })
    },
    // 获取设备
    getEquipmentAccount (val) {
      const params = {
        deviceNameOrNumber: val,
        ifBuildBox: true,
        schemeId: this.location.id,
        schemeLevel: this.location.level,
        pageSize: 10000,
        pageNum: 1
      }
      return getEquipmentAccount(params)
    },
    /**
     * 选择组织机构树节点
     * @param {number} val
     */
    _changeTreeNode: function (val) {
      if (val.id && val.label && val.hash) {
        this.location.id = val.id
        this.location.level = val.level
        this.location.label = val.label
        this.location.hash = val.hash
        // 获取设备
        this.getEquipmentAccount().then(res => {
          this.machineOptions = res.data.list.map(item => {
            return {
              ...item,
              label: item.name,
              value: item.boxStrId
            }
          })
        })
      } else {
        this.location = {
          id: null,
          level: null,
          label: '',
          hash: ''
        }
      }
    },
    // 筛选设备
    filterMachineFn (val, update) {
      this.getEquipmentAccount(val)
        .then(res => {
          update(() => {
            this.machineOptions = res.data.list.map(item => {
              return {
                ...item,
                label: item.name,
                value: item.boxStrId
              }
            })
          })
        })
    },
    // 切换设备获取内外部存储
    changeMachine (opt) {
      if (!opt.boxStrId) {
        this.noticeMessage('该设备未绑定盒子')
        return
      }
      let params = {
        boxId: opt.boxStrId,
        requestId: this.requestId
      }
      this.fileLoading = true
      this.actFile = null
      this.onSubscribe(opt.boxStrId)
      getStoreInfo(params)
      this.client.onMessageArrived = (message) => {
        let data = JSON.parse(message.payloadString)
        try {
          if (data.request_id === this.requestId) {
            if (data.code === 200) {
              let inside = null, external = null, tabList = []
              // 判断是否有外部存储
              if (data.cnc) {
                inside = {
                  boxId: opt.boxStrId,
                  id: 1,
                  label: '内部存储',
                  volumeUse: data.cnc_use,
                  volume: data.cnc,
                  source: 'machine',
                  position: 'cnc',
                  level: 6,
                  path: '/'
                }
                tabList.push(inside)
              }
              // 判断是否是内部存储
              if (data.box) {
                external = {
                  boxId: opt.boxStrId,
                  id: 2,
                  label: '外部存储',
                  volumeUse: data.box_use,
                  volume: data.box,
                  source: 'machine',
                  position: 'box',
                  level: 6,
                  path: '/'
                }
                tabList.push(external)
              }
              this.tabList = tabList
              this.tab = tabList[0].position
              this.changeStore(this.tab)
            } else {
              console.error('获取列表失败')
              this.errMessage(`获取列表失败,${boxCodeErr[data.code]}`)
            }
          }
        } catch (e) {
          console.error(e)
          this.errMessage('获取列表失败')
        }
      }
    },
    // 处理通过设备获取内外存储信息
    changeStore (tab) {
      this.getFiles('/')
    },
    getFiles (path = '/') {
      let tabInfo = this.tabList.find(item => item.position === this.tab)
      let params = {
        about: tabInfo.position,
        boxId: tabInfo.boxId,
        requestId: this.requestId,
        path: path
      }
      this.onSubscribe(tabInfo.boxId)
      this.fileLoading = true
      this.actFile = null
      getFileInfo(params)
      this.client.onMessageArrived = (message) => {
        let data = JSON.parse(message.payloadString)
        try {
          if (data.request_id === this.requestId) {
            if (data.code === 200) {
              // 判断是否有外部存储
              if (data.hasOwnProperty('box')) {
                let { dirData, fileData } = this.initMachineNodeData(params, data.box, 'box')
                this.files = [].concat(dirData, fileData)
              }
              if (data.hasOwnProperty('cnc')) {
                let { dirData, fileData } = this.initMachineNodeData(params, data.cnc, 'cnc')
                this.files = [].concat(dirData, fileData)
              }
            } else {
              console.log('获取列表失败')
              this.errMessage(`获取列表失败,${boxCodeErr[data.code]}`)
            }
            this.fileLoading = false
          }
        } catch (e) {
          console.error(e)
          this.errMessage('获取列表失败')
          this.fileLoading = false
        }
      }
    },
    // 初始化文件数据
    initMachineNodeData (node, info, source) {
      let dirData = [], fileData = []
      info.forEach((item, index) => {
        // 文件夹数据
        if (item.type === 0) {
          dirData.push({
            id: index + 1,
            boxId: node.boxId,
            label: item.name,
            size: item.size,
            isFile: false,
            icon: 'img:statics/svg/file-icon.svg',
            source: 'machine',
            position: source,
            type: 'other',
            path: node.path + item.name + '/',
            timestamp: parseInt(item.modify_time * 1000)
          })
        } else if (item.type === 1) { // 文件数据
          let type = getFiletype(item.name)
          fileData.push({
            id: index + 1,
            boxId: node.boxId,
            label: item.name,
            size: item.size,
            isFile: item.type === 1,
            icon: 'img:statics/svg/' + type + '.svg',
            source: 'machine',
            position: source,
            type,
            path: node.path + item.name,
            timestamp: parseInt(item.modify_time * 1000)
          })
        }
      })
      return { dirData, fileData }
    },
    // 订阅并发送消息,订阅主题是获取盒子列表，删除，重命名，内部存储发送结果
    onSubscribe (boxId) {
      this.boxId = boxId
      console.log(`${this.CommonConfig.mqttConfig.MQTT_TOPIC.machineFileInfo.subscribeTopic}${this.boxId}`)
      // 订阅主题
      this.client.subscribe(
        `${this.CommonConfig.mqttConfig.MQTT_TOPIC.machineFileInfo.subscribeTopic}${this.boxId}`,
        { qos: 2 }
      )
    },
    // 选择文件,这里只允许单选
    setFile (event, file) {
      console.log(file)
      clearTimeout(this.clickTime)
      this.clickTime = setTimeout(() => {
        if (file.isFile) {
          this.actFile = file
        }
      }, 250)
    },
    // 双击进入子级文件夹
    dblclickE (file) {
      clearTimeout(this.clickTime)
      if (!file.isFile) {
        this.actFile = []
        this.curDirPath = file.path
        this.getFiles(this.curDirPath)
      }
    },
    // 返回
    back () {
      if (this.curDirPath.length === 0 || this.curDirPath === '/') {
        return false
      }
      let pathArr = this.curDirPath.split('/')
      console.log(pathArr)
      pathArr = pathArr.slice(0, pathArr.length - 2)
      this.curDirPath = pathArr.join('/') + '/'
      this.getFiles(this.curDirPath)
    },
    // 提交
    submit () {
      this.$emit('submit', this.actFile)
      this.hideDialog()
    },
    // 失败提示
    errMessage (message) {
      this.$q.dialog({
        title: `<p class="dialog-notice-title">
<i class="iconfont icontubiao-52" ></i> 提示</p>`,
        message: message,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        }
      })
    },
    // 注意提示
    noticeMessage (message) {
      this.$q.dialog({
        title: `<p class="dialog-notice-title">
<i class="iconfont icontubiao-28" ></i> 提示</p>`,
        message: message,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        }
      })
    }
  },
  components: {
    SelectTree,
    FileItem
  }
}
</script>

<style scoped lang="stylus">
.form-inline{
  display flex
  align-items center
}
.content{
  padding 5px 10px 20px
  border-top 1px solid #d3d3d3
  border-bottom 1px solid #d3d3d3
  >>>.q-tabs__content--align-justify .q-tab{
    flex 0 0 auto
  }
  .scorll-content{
    border 1px solid #d3d3d3
    border-radius 6px
  }
  .file-list{
    padding 10px 5px
    display flex
    flex-wrap wrap
  }
  .back-btn{
    position absolute
    top 12px
    right 20px
  }
}
</style>
